<template>
  <div class="app-container tDiv " :class="pjClass?'tDiv1':''">
    <!--页面内容-->
    <div class="bd">
      <span class="titleSpan"><svg data-v-c8a70580="" aria-hidden="true" class="svg-icon"><use data-v-c8a70580="" xlink:href="#icon-component"></use></svg>筛选项
      <el-tooltip class="item" effect="dark" content="增加/删除筛选项配置" placement="right">
        <el-button icon="el-icon-edit-outline" circle size="mini" @click="handleRef('filter')"></el-button>
      </el-tooltip></span>
      <div class="rightD">
        <span class="tips">可拖拽选项文字进行排序，点击选项文字调整宽度</span>
        <!-- {{ filterCreateList }} -->
        <el-card class="box-card">
          <span v-if="filterCreateList.length === 0" class="tipSpan">暂无数据</span>
          <drag-filter @gridReloadNoId="gridReloadNoId" v-if="resetFlag" :filterCreateList="filterCreateList" @change="formChange" ref="DragFilter"></drag-filter>
        </el-card>
      </div>

    </div>

    <div class="bd">
      <span class="titleSpan"><svg data-v-c8a70580="" aria-hidden="true" class="svg-icon"><use data-v-c8a70580="" xlink:href="#icon-component"></use></svg>数据列表
       <el-tooltip class="item" effect="dark" content="增加/删除数据表格列表配置" placement="right">
          <el-button icon="el-icon-edit-outline" circle size="mini" @click="handleRef('table')"></el-button>
        </el-tooltip></span>
      <div class="rightD">
        <span class="tips">可拖拽表头进行排序，移动边框调整列宽</span>
        <el-card class="box-card tableCard">
          <drag-table @gridReloadNoId="gridReloadNoId" v-if="resetFlag" :head-columns="tableCreateList" @header-dragend="colChange" @change="tableSortSet" ref="DragHead"></drag-table>
        </el-card>
      </div>
    </div>


    <!--预览-->
    <el-drawer
      direction="btt" size="90%">
      <el-row id="modeBtn">
        <el-tooltip class="item" effect="dark" content="保存" placement="top">
          <el-button type="success" icon="el-icon-check" circle size="mini" @click="configPageSave"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="还原" placement="top" >
          <el-button type="warning" icon="el-icon-refresh-right" circle size="mini" @click="resetPage"></el-button>
        </el-tooltip>
      </el-row>
    </el-drawer>

    <!--添加时穿梭框-->
    <el-dialog
      :title="addTitle"
      :visible.sync="addFlag"
      :close-on-click-modal="false"
      width="75%"
      :before-close="addDialogClose">
      <template >
        <div><span class="tipSpan1"><i class="el-icon-info"></i>已选项可拖动来调整排序</span></div>
        <div>
          <DraggableTransfer v-loading="addLoading"
                             element-loading-text="正在保存数据..."
                             :defaultProps="{ children: 'list', label: 'name', key: 'id', parentKey: 'classify' }"
                             :leftOriginalList="unselectedList"
                             :rightOriginalList="selectedList"
                             :leftInitList="leftInitList"
                             @change="handelSelectedChange"/>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveTransfer">确 定</el-button>
          <el-button @click="cancel('addDialog')">取 消</el-button>
        </div>
      </template>

    </el-dialog>
    <div class="footDiv" :style="pjClass?'width:98.3%':''">
      <el-button type="primary" @click="configPageSave">保 存</el-button>
      <el-tooltip class="item" effect="dark" content="重置排序和表格列宽" placement="top">
        <el-button @click="resetPage">重 置</el-button>
      </el-tooltip>
    </div>
    <select-field @gridReloadNoId="gridReloadNoId" ref="selectField" />
  </div>
</template>
<style scoped>
.rightD{
  width: 83.5%!important;
  padding: 10px;
  margin-top: 10px;
}
.el-card.box-card.is-always-shadow {
  width: 100%!important;
  left: 0%!important;
  position: relative;
}
.svg-icon[data-v-c8a70580]{
  width: 1.5em;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
.el-collapse-item__header{
  border-top: 1px solid #e6ebf5;
}
.el-table__empty-text{
  width: auto;
}
span.titleSpan{
  display: inline-block;
  float: left;
  text-align: center;
  position: relative;
  width: 16.3%;
  font-weight: bolder;
  letter-spacing: 1px;
  color: #494949;
  padding-top: 1%;
}
span.tipSpan {
  color: #909399;
  display: block;
  text-align: center;
  position: relative;
  top: 10px;
  font-size: 14px;
}
span.tips {
  position: relative;
  right: 0%;
  text-align: right;
  top: -1%;
  margin-top: -.5%;
  margin-bottom: .2%;
  font-size: 12px;
  display: block;
  color: gray;
}
.el-tabs__header{
  margin: 0;
}
.tDiv{
  padding: 0px;
  overflow-y:auto;
  height: 100%;
  border: 1px solid #ededed;
}
.tDiv1{
  margin: 10px;
  height: 85vh;
}
.tableCard{
  margin-bottom: 10px;
}
.tableCard>.el-card__body {
  padding: 15px 20px 8px 20px!important;
}
.tipSpan1{
  position: relative;
  left: 82%;
  color: #8f8f8f;
  font-size: 9px;
}
.bd {
  display: flex;
  align-items: center;
}
.footDiv {
  width: 100%;
  height: fit-content;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.tipSpan1 {
  font-size: 14px;
}
.el-dialog__body {
  padding: 0 20px;
}
</style>
<script>
import DraggableTransfer from '@/components/DraggableTransfer';
import DragTable from "@/components/DraggableTable";
import DragFilter from "@/components/DraggableFilter";
import {addRefFieldForFilters} from "@/api/form/field";
import { getConfig,gridConfigView,updateGridConfig,getGridConfig,listGridConfig,addGridConfig,updateGridConfigParts } from "@/api/form/modelfield";
import SelectField from "@/views/form/config/model/selectfield.vue";
export default {
  name: "GridConfig",
  components: {
    DraggableTransfer,DragTable,DragFilter,SelectField
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 新增穿梭框显示
      addFlag:false,
      addTitle: '',
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open:false,
      filterForm:{},
      // 筛选项过滤器 实时页面数据
      filterCreateList:[],
      tableCreateList:[],
      // 模型全部属性数据
      totalList:[],
      // 用一个字符串来保存当前双击的是哪一个单元格
      currentCell: null,
      //  筛选项修改表单
      //filterEditForm:{id: null},
      // 表格配置修改表单内
      //tableEditForm:{id: null},
      // 穿梭框
      unselectedList: [],
      selectedList: [],
      leftInitList: [],
      addLoading: false,
      colWidthChangeList:[],
      tableSortChangeList:[],
      filterSortChangeList:[],
      modelId: '',
      resetFlag: true,
      pjClass: false
    };
  },
  mounted(){
    this.$nextTick(() => {
      var _this = this;
      window.addEventListener('resize',function(){
        _this.$layoutresize();
      });
    });
  },
  created() {
    this.modelId = localStorage.getItem("ls_model_id");
    this.pjClass = true;
    this.getFilterAll();
    this.getTableAll();
  },
  methods: {
    /**页面整体刷新*/
    gridReload(modelId){
      this.modelId = modelId;
      this.getFilterAll();
      this.getTableAll();
    },
    /** 选择引用属性 */
    handleRef(type) {
      this.$refs.selectField.showDialog1(this.modelId,type);
    },
    /**页面整体刷新*/
    gridReloadNoId(){

      this.getFilterAll();
      this.getTableAll();
    },
    /** 获取模型绑定的筛选项数据 */
    async getFilterAll(){
      let params = {
        modelId: this.modelId,
        type:'filter'
      };
      await gridConfigView(params).then(response => {
        if (!response.data) return;
        this.filterCreateList = response.data;
        if (this.$refs.DragFilter)this.$refs.DragFilter.updateList(response.data);
      });
    },
    /** 获取模型绑定的列表数据 */
    async getTableAll(){
      await gridConfigView({modelId: this.modelId, type:'table'}).then(response => {
        this.tableCreateList = response.data;
        if (this.$refs.DragHead)this.$refs.DragHead.updateList(this.tableCreateList);
        setTimeout(() => {
          this.$layoutresize();
        }, 100);
      });
    },
    addDialogClose(){
      this.addFlag = false;
    },
    cancel(f) {
      if(f==='filter'){
        this.open = false;
        this.filterEditForm = {};
      } else if( f === 'table'){
        this.open = false;
        this.tableEditForm = {};
      } else{
        this.addDialogClose();
      }
    },
    // 通过模型id查询全部绑定全部属性
    async getAllGridByModelId() {
      if (this.modelId !=='' ){
        let query ;
        if (this.pjClass){
          query = {delFlag: 0,type:'class'};
        } else{
          query = {delFlag: 0};
        }
        await getConfig(query).then(response => {
          this.totalList = response.rows;
        })
      }
    },
    // 打开穿梭框
    async transferOpen(f){
      if(f === 'filter'){
        await this.getFilterAll();
        this.addFlag = true;
        this.addTitle = '新增筛选项配置';
        this.unselectedListInit('filter');
        this.selectedList = [];
        //this.filterCreateList.forEach((l)=> {  this.selectedList.push( {id:l.key,name:l.label,filterSortNum: l.filterSortNum}) });
        this.selectedList = this.filterCreateList;
        this.selectedList.forEach((l) => {
          var tempArr = {id:l.key,name:l.label,filterSortNum: l.filterSortNum,basicName: l.label};
          Object.assign(l,tempArr);
        });
        console.log(this.selectedList);
      } else{
        await this.getTableAll();
        this.addFlag = true;
        this.addTitle = '新增表格列表配置';
        this.unselectedListInit('table');
        this.selectedList = [];
        //this.tableCreateList.forEach((l)=> {  this.selectedList.push( {id:l.id,name:l.name,sortNum:l.sortNum}) });
        this.selectedList = this.tableCreateList;

        this.selectedList.forEach((l) => {
          console.log(l);
          var tempArr = {id:l.id,name:l.name,sortNum:l.sortNum,basicName: l.label};
          Object.assign(l,tempArr);
        });
        console.log(this.selectedList);
      }
    },
    // 穿梭框左侧初始化
    async unselectedListInit(f){
      await this.getAllGridByModelId();
      if(this.totalList){
        this.unselectedList = this.totalList.filter((l) => {
          let a = false;
          if(f ==='filter'){
            this.filterCreateList.forEach((f) => {
              if (f.fieldId === l.id) {  //if (f.key === l.id) {
                a =  true;
              }
            });
          } else{
            this.tableCreateList.forEach((f) => {
              if (f.fieldId === l.id) {
                a =  true;
              }
            });
          }
          if (!a){
            l.name = l.basicName;
            return l;
          }
        });
        this.leftInitList = this.unselectedList;
      }
    },
    // 穿梭框保存
    async saveTransfer(){
      this.addLoading = true;
      console.log(this.addTitle);
      console.log(this.selectedList);
      console.log(this.unselectedList);
      if(this.addTitle === '新增筛选项配置'){
        // 右侧最终数组
        await this.selectedList.forEach((s,i)=>{
          if (s.basicCode){ // 是属性数据
            s.filterType = 'filter';
            s.filterSortNum = i;
            s.modelId = this.modelId;
            addRefFieldForFilters(s).then(response =>{
              if (i === this.selectedList.length-1){
                this.getFilterAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            })
          } else {
            s.filterPosition = '1';
            s.filterSortNum = i;
            updateGridConfigParts(s).then(response =>{
              if (i === this.selectedList.length-1){
                this.getFilterAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            })
          }

        });
        // 左
        await this.unselectedList.forEach((u,i) =>{
          if (u.basicCode === undefined){
            u.filterPosition = '';
            updateGridConfigParts(u).then(response =>{
              if (i === this.unselectedList.length-1){
                this.getFilterAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            })
          }
        });
      } else {
        // 右侧最终数组
        this.selectedList.forEach((s,i)=>{
          if (s.basicCode) { // 是属性数据
            s.filterType = 'table';
            s.filterSortNum = i;
            s.modelId = this.modelId;
            addRefFieldForFilters(s).then(response =>{
              if (i === this.selectedList.length-1){
                this.getTableAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            })
          } else{
            s.showFlag = '0';
            s.sortNum = i;
            updateGridConfigParts(s).then(response =>{
              if (i === this.selectedList.length-1){
                this.getTableAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            });
          }

        });
        // 左
        this.unselectedList.forEach((u,i) =>{
          if (u.basicCode === undefined || u.basicCode === null){
            u.showFlag = '1';
            updateGridConfigParts(u).then(response =>{
              if (i === this.unselectedList.length-1){
                this.getTableAll();
                this.addFlag = false;
                this.addLoading = false;
              }
            })
          }
        });

      }
    },
    handelSelectedChange(data) {
      console.log(data);
      if (data.left){
        this.unselectedList = JSON.parse(JSON.stringify(data.left));
        this.selectedList = JSON.parse(JSON.stringify(data.right));
      }
    },
    /** 重置页面*/
    async resetPage(){
      this.colWidthChangeList = [];
      this.tableSortChangeList = [];
      this.filterSortChangeList = [];

      await this.getFilterAll();
      await this.getTableAll();
      this.resetFlag = false;
      this.$nextTick(()=>{
        this.resetFlag = true;
      })
    },
    colChange(newWidth, oldWidth, column, event){
      this.colWidthChangeList.push({
        id: column.property,
        colWidth: newWidth
      });
    },
    async configPageSave(){
      // 保存 遍历表格列宽
      try {
        await this.colWidthChangeList.some((w)=>{
          updateGridConfigParts(w).then(response =>{
            if (response.code !== 200)  throw new Error("ending");
          })
        });
        // 遍历 表格顺序
        await this.tableSortChangeList.forEach((t,i)=>{
          updateGridConfigParts({id:t.id,sortNum: i}).then(response =>{
            if (response.code !== 200)  throw new Error("ending");
          })
        });
        this.filterSortChangeList.forEach((f,i)=>{
          updateGridConfigParts({id:f.key,filterSortNum: i,labelWidth:f.labelWidth,formItemWidth:f.formItemWidth}).then(response =>{
            if (response.code !== 200)  throw new Error("ending");
          })
        });
      }catch (e) {
        this.$message.error('保存失败');
        return true;
      }
      this.$message({
        message: '保存成功！',
        type: 'success'
      });
    },
    tableSortSet(data){
      this.tableSortChangeList = data.tableHead;
    },
    formChange(data){
      this.filterSortChangeList = data.list;
    }
  }
};
</script>
